const apiBaseUrl = import.meta.env.VITE_API_BASE_URL
import { useUserStore } from '../store/user'

// 封装请求函数
const request = <T>(config: RequestConfig): Promise<T> => {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore()
    const headers = {
      ...config.header,
      // 检查用户是否登录，如果登录则添加 Authorization 头
      ...(userStore.token && { Authorization: `Bearer ${userStore.token}` }),
    }
    // 显示加载中
    uni.showLoading({
      title: '加载中',
      mask: true,
    })
    uni.request({
      url: apiBaseUrl + config.url,
      method: config.method,
      data: config.data,
      header: headers,
      success: (res: any) => {
        // 隐藏加载中
        uni.hideLoading()
        if (res.statusCode >= 200 && res.statusCode < 300) {
          if (res.data.code == 200) {
            resolve(res.data as T)
          } else {
            // 请求失败提示
            uni.showToast({
              title: `${res.message}`,
              icon: 'none',
              duration: 2000,
            })
            reject(res.data as T)
          }
        } else {
          // 请求失败提示
          uni.showToast({
            title: `请求失败，状态码: ${res.statusCode}`,
            icon: 'none',
            duration: 2000,
          })
          reject(new Error(`Request failed with status code ${res.statusCode}`))
        }
      },
      fail: (err) => {
        // 隐藏加载中
        uni.hideLoading()
        // 请求失败提示
        uni.showToast({
          title: `请求失败: ${err.errMsg}`,
          icon: 'none',
          duration: 2000,
        })
        reject(err)
      },
    })
  })
}

export default request
